/**
 * 
 */
package com.jie.eclipse.pan.swtitem.table;


import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

import com.jie.eclipse.pan.data.BaseDataEntities;
import com.jie.eclipse.pan.data.BaseDataEntity;

/**
 * @author yanjie
 *
 */
public class PTable extends Table{
	protected Map<String, BaseDataEntity> colNameIndexMap = null; //记录col Nam 与 index 的对应资料
	
	public PTable(Composite parent, int style) {
		super(parent, style);
	}
	
	@Override
	protected void checkSubclass() {
		// TODO Auto-generated method stub
	}
	
	public void reloadColumns(){
		this.colNameIndexMap = new LinkedHashMap<String, BaseDataEntity>();
		for (int i = 0; i < this.getColumns().length; i++) {
			PTableColumn col = (PTableColumn)this.getColumn(i);
			BaseDataEntity data = new BaseDataEntity();
			data.spsv("name", col.getName());
			data.spsv("text", col.getText());
			data.spiv("index", i);
			data.spov("column", col);
			this.colNameIndexMap.put(col.getName(), data);
		}
	}
	
	public void addRecord(BaseDataEntity row){
		PTableItem item = new PTableItem(this, SWT.NONE);
		for (Iterator iterator = this.colNameIndexMap.keySet().iterator(); iterator.hasNext();) {
			String name = iterator.next().toString();
			int index = this.getColumnIndex(name); 
			item.setText(index, row.gpsv(name));
			item.setData(row);
			if(row.gpov(name+"_img") instanceof Image)
				item.setImage(index,(Image)row.gpov(name+"_img"));
		}
	}
	
	public void ReloadTableItemRecord(TableItem item,BaseDataEntity row){
		for (Iterator iterator = this.colNameIndexMap.keySet().iterator(); iterator.hasNext();) {
			String name = iterator.next().toString();
			int index = this.getColumnIndex(name); 
			item.setText(index, row.gpsv(name));
		}
	}
	
	public void ReLoadRecord(BaseDataEntities rows){
		this.removeAll();
		for (int i = 0; rows != null && i < rows.size(); i++) {
			BaseDataEntity row = rows.get(i);
			PTableItem item = new PTableItem(this, SWT.NONE);
			for (Iterator iterator = this.colNameIndexMap.keySet().iterator(); iterator.hasNext();) {
				String name = iterator.next().toString();
				int index = this.getColumnIndex(name); 
				item.setText(index, row.gpsv(name));
				item.setData(row);
			}
		}
	}
	
	
	
	public int getColumnIndex(String name){
		int index = -1;
		if(this.colNameIndexMap.containsKey(name))
			index = this.colNameIndexMap.get(name).gpiv("index");
		return index;
	}
	
	public String getColumnName(int col) {
		PTableColumn column = (PTableColumn)this.getColumn(col);
		return column.getName();
	}
	
}
